package done;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;


public class WindowViewer extends SwingWorker<Boolean, Boolean> implements
		ScaleWriter {

	private JPanel threadPanel;
	private double nextData = 0;
	private String nextTime = new String();
	private JLabel windowOpen,windowClosed;
	private int windowStatus=-1;
	private LinkedList<Information> list = new LinkedList<Information>();

	public WindowViewer() {
		list = new LinkedList<Information>();
		windowStatus=-1;
		windowOpen=new JLabel("Window Open");
		windowClosed=new JLabel("Window Closed");
		windowOpen.setForeground(Color.BLUE);
		windowOpen.setBounds(new Rectangle(5, 5, 90, 25));
		windowClosed.setBounds(new Rectangle(5, 5, 90, 25));
		windowClosed.setForeground(Color.DARK_GRAY);
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		Information i;	
		while ((i = list.poll()) != null ) {
			Thread.sleep(100);
			nextData = i.getData();
			nextTime = i.getTime();
			if((int)nextData==0)
			{
				if(windowStatus==0);
				else
				{
					windowStatus=0;
					modifyPanel(windowStatus,nextTime);
				}
			}
			if((int)nextData==1)
			{
				if(windowStatus==1);
				else
				{
					windowStatus=1;
					modifyPanel(windowStatus,nextTime);
				}
			}

		}
		if(i==null && hasFinished==false){		
			while(list.size()<1 && hasFinished==false)
				{
					Thread.sleep(10);
				}
				doInBackground();
			}else 
			{
				System.out.println("done2");
				return true;
			}		
		System.out.println("done1");
		return true;
	}

	private void modifyPanel(int type,String time)
	{
		threadPanel.removeAll();
		switch(type)
		{
		case 0:
		{
			windowClosed.setToolTipText("Window Closed at "+time);
			threadPanel.add(windowClosed,null);
			break;
		}
		case 1:
		{
			windowOpen.setToolTipText("Window opened at "+time);
			threadPanel.add(windowOpen,null);
			break;
		}
		}		
		
		threadPanel.setPreferredSize(new Dimension(100, size));
		threadPanel.setSize(new Dimension(100, size));
		threadPanel.repaint();
	}
	
	@Override
	public void writeNext(Information i) {
			list.add(i);
	}

	@Override
	public void setPanel(JPanel panel) {
		threadPanel = panel;

	}

	private boolean hasFinished = false;

	@Override
	public void finished() {
		hasFinished = true;
	}

	
	public void runWorker()
	{
		this.execute();
	}
}